package com.netease.nim.demo.database.contact;

import android.database.Cursor;

import com.netease.nim.demo.contact.model.Buddy;
import com.netease.nim.demo.database.base.DatabaseHelper;

import java.util.ArrayList;
import java.util.List;

public class ContactDatabaseHelper {

	private ContactDatabase database;

	public ContactDatabaseHelper(ContactDatabase openedDB) {
		database = openedDB;
	}

	/****
	 * ******************************* buddy *************************************
	 */
	private static final String buddyListTableName = "buddylist";
	private static final String buddyClomums =
				"account," +
				"name," +
				"icon," +
                "type"
				;

	public void addBuddy(Buddy buddy) {
		List<Buddy> buddies = new ArrayList<Buddy>(1);
		buddies.add(buddy);
		addBuddies(buddies);
	}

	public void addBuddies(List<Buddy> buddies) {
		// update buddy list table
		String buddySql = "insert or replace into " + buddyListTableName + " (" + buddyClomums + ")";
		String _buddySql = "";

		for (Buddy buddy : buddies) {
			if (_buddySql.length() == 0) {
				_buddySql += " select '";
			} else {
				_buddySql += " union select '";
			}

			_buddySql += (buddy.getAccount() + "','" + DatabaseHelper.escapeQuotes(buddy.getName()) + "','"
					+ buddy.getIcon() + "','" + 0 + "'");

			if (_buddySql.length() > 10000) { // sql语句长度限制

				database.exeSQL(buddySql + _buddySql);
				_buddySql = "";
			}
		}

		if (_buddySql.length() > 0) {
			database.exeSQL(buddySql + _buddySql);
		}
	}

    /**
     * 返回所有好友（包括群成员）
     */
	public List<Buddy> getBuddies() {
		String sql = "select " + buddyClomums + " from " + buddyListTableName;
		Cursor cursor = database.rawQuery(sql);
		if (cursor == null) {
			return new ArrayList<Buddy>();
		}

		List<Buddy> buddies = new ArrayList<Buddy>(cursor.getCount());

		while (cursor.moveToNext()) {
			buddies.add(buddyFromCursor(cursor));
		}

		if (!cursor.isClosed()) {
			cursor.close();
		}

		return buddies;
	}

	public Buddy getBuddy(String account) {
		String sql = "select " + buddyClomums + " from " + buddyListTableName + " where account='" + account + "'";
		Cursor cursor = database.rawQuery(sql);

		if (cursor != null) {
			Buddy buddy = null;
			if (cursor.moveToNext()) {
				buddy = buddyFromCursor(cursor);
			}
			if (!cursor.isClosed()) {
				cursor.close();
			}
			return buddy;
		}

		return null;
	}

	public void removeBuddy(String account) {
		String sql = "delete from " + buddyListTableName + " where account='" + account + "'";
		database.exeSQL(sql);
	}

	private Buddy buddyFromCursor(Cursor cursor) {
		Buddy buddy = new Buddy();

		int column = 0;
		buddy.setAccount(cursor.getString(column++));
		buddy.setName(cursor.getString(column++));
		buddy.setIcon(cursor.getInt(column++));

		return buddy;
	}
}
